import {
	asyncRouterMap,
	constantRouterMap
} from "@/router"
import Vue from 'vue'
import {
	getMenubyUser
} from '@/api/index'
/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permslist, route) {
	if (route.meta && route.meta.permission) {

		let flag = false;
		if (route.meta.permission.includes('home')) {
			return true
		}
		console.log(route.meta.permission);
		for (let i = 0, len = permslist.length; i < len; i++) {
			flag = route.meta.permission.includes(permslist[i])
			if (flag) {
				return true
			}
		}
		return false
	}
	return true
}

function filterAsyncRouter(routerMap) {
	const accessedRouters = routerMap.filter(route => {
		if (route && (route.type == 1 || route.type == 0)) {
			if (route.children && route.children.length > 0) {
				route.children = [...filterAsyncRouter(route.children)];
			}
			return true
		}
		return false

	})
	return accessedRouters
}

function setAsyncRouter(routerMap) {
	let accessedRouters = []
	routerMap.forEach(route => {
		let path = route.url;
		let component = '';
		if (route.component && route.component.indexOf('http') > -1) {
			component = 'components/Myiframe/index.vue';
			path = route.component;
			// console.log(path);
		} else {
			if (route.type == 0) {
				/* if(route.name=='首页'){
					component='layouts/HomeLayout.vue'
				}else if(route.name=='互动课堂'){
					component = 'layouts/EmptyRouteView.vue'
				} */
				if(route.perms=='home'){
					component='layouts/HomeLayout.vue'
				/* }else if(route.perms=='impromptuQA'){ */
				}else if(route.perms=='doExercise'){
					component = 'layouts/EmptyRouteView.vue'
				}else{
					component='layouts/BasicLayout.vue'
					//component='layouts/MainLayout.vue'
				}
			} else if (route.component == 'EmptyRouteView') {
				component = 'layouts/EmptyRouteView.vue'
			} else {
				component = route.component || 'components/404/index.vue';
			}
		}
		//console.log('component', component, route.type, component == 'EmptyRouteView')
		if (route && (route.type == 1 || route.type == 0)) {
			let namelist = route.url.split('/');
			let name = namelist[namelist.length - 1];
			if (name.indexOf(':') > -1) {
				name = namelist[namelist.length - 2]
			}
			let newroute = {
				path: route.url,
				name: route.componentName || name,
				redirect: route.redirect,
				component: resolve => require(['../../' + component], resolve),
				hidden: route.hiddenInMenu == 0,
				meta: {
					title: route.name,
					icon: route.icon,
					url: path,
					permissionList: route.perms,
					keepAlive: route.cacheRoute == 0,
					name: route.component == 'EmptyRouteView' ? 'EmptyRouteView' : '',
					hidden: route.hiddenInMenu == 0,
				}
			}
			if (route.children && route.children.length > 0) {
				newroute.children = [...setAsyncRouter(route.children)];
				if (newroute.children.some(item => !item.hidden)) {
					newroute.hideChildrenInMenu = false
				} else {
					newroute.hideChildrenInMenu = true
				}
				if (route.redirect == 'redirect') {
					for (var i = 0; i < route.children.length; i++) {
						if (route.children[i].type == 1 || route.children[i].type == 0) {
							newroute.redirect = route.children[i].url;
							break;
						}
					}
				}
			}
			accessedRouters.push(newroute)
		}
	})
	//console.log("组合路由"+JSON.stringify(accessedRouters))
	return accessedRouters
}

/* 将多维数组拍成二维数组。解决多级路由无法缓存的问题 */
const formatRouter = (routes, newRoutes = []) => {
	routes.map(item => {
		if (!!item) {
			if (item.children && item.children.length > 0) formatRouter(item.children, newRoutes);
			if (item.meta.name == 'EmptyRouteView') {
				//newRoutes.push(item.children);
				if (item.children && item.children.length > 0) {
					item.children.forEach(subitem => {
						newRoutes.push(subitem)
					})
				}
				let {
					children,
					...parentItem
				} = item
				newRoutes.push(parentItem)
			} else {
				newRoutes.push(item);
			}
		}

	})
	return newRoutes;
}

function setredirect(routerMap) {
	console.log('routerMap', routerMap)
	routerMap.forEach(route => {
		if (route.redirect == 'redirect') {

			if (route.children && route.children.length > 0) {
				route.redirect = route.children[0].path;

				route.children = setredirect(route.children)
			}
			// return true
		}
		// return false
	})
	return routerMap
}
const permission = {
	state: {
		routers: constantRouterMap,
		addRouters: [],
		buttenpremissions: [],
		menuId: '',
		hasGetMenu: false
	},
	mutations: {
		SET_ROUTERS: (state, routers) => {
			state.routers = constantRouterMap.concat(routers);
			/* 在这里将roter 变成最多二级 */
			let flatRoutes = routers.map(item => {
				let info = {
					...item
				};
				if (info.children && info.children.length > 0) {
					let children = formatRouter(info.children);
					info.children = children;
				}
				return info
			})
			state.addRouters = [...flatRoutes]
		},
		SET_PERMSLIST: (state, permslist) => {
			state.permslist = permslist;
			sessionStorage.setItem('buttenpremissions', JSON.stringify(permslist))
		},
		SET_menuId: (state, menuId) => {
			state.menuId = menuId;
		},
		SET_menuState: (state, menustate) => {
			state.hasGetMenu = menustate;
		}
	},

	actions: {

		GenerateRoutes({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getMenubyUser().then((da) => {
					let menulist = da.data || [];
					let permslist = '';
					let router = [];
					if (menulist && menulist.length > 0) {
						
						/* 获取权限列表 */
						permslist = JSON.stringify(menulist).match(/(?=\"perms\":")([^\,]*)(?=\,)/g)
							.join(',').replace(
								/"perms":/g,
								'').replace(/\"/g, '').split(',');
						const asyncRouterMapList = setAsyncRouter(menulist);

						// let list = setredirect(asyncRouterMapList)
						router = [...asyncRouterMapList];

					} else {
						router.push({
							path: '/',
							hidden: true,
							redirect: '/usercenter',
						})
					}
					router.push({
						path: '*',
						redirect: '/404',
						hidden: true
					})
					commit('SET_ROUTERS', router)
					commit('SET_menuState', true);
					commit('SET_PERMSLIST', permslist);
					resolve()
				})


			})
		}
	}
}

export default permission
